class ElectionController < ApplicationController
  layout 'layouts/standard_layout'
  def index
    unless params[:id]
      redirect_to :action=>"list_elections"
      return
    end
    @election = Election.find(params[:id])
    @page_title = "Election:  #{@election.name}"
    @page_title = @election.name
    @event = @election.event    
    @user = Person.find_by_username(session[:username]) if session[:username]
    @items = @election.event.items.find(:all, :conditions=>@election.conditions, :order=>"name")
  end

  def vote
    @election = Election.find(params[:election_id])
    @page_title = "Ballot error:  #{@election.name}"
    unless person = Person.find_by_username(session[:username])      
      flash[:notice] = "You are not signed in properly!"
      render :template=>'voting_error'
      return
    end
    
    unless @election.open?
      flash[:notice] = "This election is not currently open, sorry."
      redirect_to :template=>'voting_error'
      return      
    end
    @page_title = "Ballot submitted:  #{@election.name}"
    params[:item].each do | item_id, score |
      
      vote = Vote.find_or_create_by_item_id_and_election_id_and_person_id(item_id.to_i, @election.id, person.id)
      next if score == "0" and vote.new_record?
      if score == "0" and !vote.new_record?
        Vote.delete(vote.id)
        next
      end
      vote.item = Item.find(item_id)
      vote.person = person
      vote.election = @election
      vote.score = score.to_i
      vote.save
    end
  end
  
  def results
    unless params[:id]
      redirect_to :action=>'list_elections'
      return    
    end
    @election = Election.find(params[:id])
    @page_title = "Results:  #{@election.name}"
    @results = {}
    items = []
    @election.votes.each do | v |
      items << v.item unless items.index(v.item)
    end
    @scores = []
    machine_readable = []
    items.each do | i |
      score = @election.votes.sum(:score, :conditions=>["item_id = ?", i.id]).to_s
      @scores << score.to_i unless @scores.index(score.to_i)
      @results[score] ||=[]
      @results[score] << i
      machine_readable << {:id=>i.id,:title=>i.name,:description=>i.description,:score=>score}
    end

    ActiveSupport::JSON.unquote_hash_key_identifiers = false
    respond_to do |format|
      format.html 
      format.json { render :json => machine_readable.to_json }
      format.xml  { render :xml => machine_readable.to_xml }
    end    
  end
  
  def list_elections
    @open = []
    @closed = []
    Election.find(:all).each do | elect |
      if elect.open?
        @open << elect
      else
        @closed << elect
      end
    end
  end
end
